/* eslint-disable standard/no-callback-literal */
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { createContainer } from 'utils/hoc'
import ContentBox from 'components/contentBox'
import Filters from 'components/common/filters'
import CustomTable from 'components/common/table'
import { Form, message, Popconfirm, Button, Switch, Modal, Icon, Input, Upload, Radio, DatePicker } from 'antd'
import { widgetType } from 'constants'
import PropTypes from 'prop-types'
import Style from './radio.css'
import moment from 'moment'

const formItemLayout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 16 }
}
const { TextArea } = Input
class IndexForm extends Component {
  static propTypes = {
    form: PropTypes.object,
    getRadioList: PropTypes.func,
    radioData: PropTypes.object
  }
  constructor (props) {
    super(props)
    this.state = {
      pageNo: 1,
      pageSize: 20,
      params: {},
      editParams: {},
      defaultFileList: []
    }
    this.search = this.search.bind(this)
    this.reset = this.reset.bind(this)
    this.onPageChange = this.onPageChange.bind(this)
    this.onShowSizeChange = this.onShowSizeChange.bind(this)
    this.onSelectChange = this.onSelectChange.bind(this)
    this.handleAdd = this.handleAdd.bind(this)
    this.handleCancel = this.handleCancel.bind(this)
    // this.radioOnChange = this.radioOnChange.bind(this)
    this.handleOk = this.handleOk.bind(this)
    this.imageChange = this.imageChange.bind(this)
    this.beforeUpload = this.beforeUpload.bind(this)
  }

  getFilterCols (category, author) {
    return [
      {
        label: '广告名称',
        id: 'name',
        widget: widgetType.input,
        placeholder: '请输入'
      }, {
        label: '开始时间',
        id: 'startTimeSearch',
        widget: widgetType.datePicker,
        placeholder: '请选择'
      }, {
        label: '到期时间',
        id: 'endTimeSearch',
        widget: widgetType.datePicker,
        placeholder: '请选择'
      }
    ]
  }

  getTableCols () {
    return [
      {
        title: '编号',
        dataIndex: 'code',
        key: 'code',
        width: 100,
        sorter: (a, b) => a.code - b.code
      },
      {
        title: '视频广告名称',
        dataIndex: 'name',
        key: 'name',
        width: 100
      },
      {
        title: '广告时长(秒)',
        dataIndex: 'timeLength',
        key: 'timeLength',
        width: 100
      },
      {
        title: '时间',
        dataIndex: 'price',
        key: 'price',
        width: 100,
        render: (text, record) => <>
          <div>开始时间：{record.startTime}</div>
          <div>结束时间：{record.endTime}</div></>
      },
      {
        title: '上线/下线',
        dataIndex: 'status',
        key: 'status',
        width: 100,
        render: (text, record) => <Switch defaultChecked={text === 1} size='small' onChange={(e) => this.handleChange(e, record.id)} />
      },
      {
        title: '操作',
        dataIndex: 'operate',
        key: 'operate',
        render: (text, record) => {
          return <>
            <a className={Style['a-btn']} onClick={() => this.handleEdit(record)}>编辑</a>
            <Popconfirm placement='top' title='确认是否删除' onConfirm={() => this.handleDel(record.id)}>
              <a className={Style['a-btn']}>删除</a>
            </Popconfirm>
          </>
        },
        width: 100
      }
    ]
  }

  reset () {
    this.setState({
      pageNo: 1,
      pageSize: 20,
      params: {}
    })
    this.props.getRadioList({
      pageNo: 1,
      pageSize: 20
    })
  }
  search (values = {}) {
    if (values.endTimeSearch) {
      values.endTime = values.endTimeSearch.format('YYYY-MM-DD HH:mm:ss')
      delete values.endTimeSearch
    }
    if (values.startTimeSearch) {
      values.startTime = values.startTimeSearch.format('YYYY-MM-DD HH:mm:ss')
      delete values.startTimeSearch
    }
    const { pageSize, pageNo } = this.state
    values.pageNo = pageNo
    values.pageSize = pageSize
    this.setState({
      params: values
    })
    this.props.getRadioList(values)
  }
  handleAdd () {
    this.setState({
      showModal: true,
      formStatus: 'add',
      title: '新增视频广告',
      editParams: {},
      radio: null
    })
  }

  handleEdit (params) {
    this.setState({
      showModal: true,
      formStatus: 'edit',
      title: '编辑视频广告',
      editParams: params,
      radio: params.video
    })
  }

  handleCancel () {
    this.setState({
      showModal: false,
      editParams: {}
    })
  }

  onPageChange (pageNo, pageSize) {
    const { params } = this.state
    params.pageNo = pageNo
    params.pageSize = pageSize
    this.setState({
      pageNo
    })
    this.props.getRadioList(params)
  }

  onShowSizeChange (current, pageSize) {
    this.setState({
      pageSize
    })
    const { params } = this.state
    params.pageNo = current
    params.pageSize = pageSize
    this.props.getRadioList(params)
  }

  // 删除
  handleDel (id) {
    this.props.delRadio({
      videoId: id
    })
  }

  handleChange (value, id) {
    this.props.changeRadioStatus({
      videoId: id,
      status: value ? 1 : 0
    })
  }

  onSelectChange (selectedRowKeys, selectedRows) {
    let restoreList = []
    selectedRows.map(item => {
      restoreList.push(item.commodityId)
    })

    this.setState({
      restoreList,
      selectedRowKeys
    })
  }

  imageChange ({ file, fileList, event }) {
    if (file.status !== 'uploading') {
      this.setState({
        loading: true
      })
    }

    if (file.status === 'error') {
      this.setState({
        loading: false
      })
      message.error('上传失败')
    }

    if (file.status === 'done') {
      this.setState({
        loading: false,
        radio: file.response && file.response.data.imageUrl
      })
    }

    if (!file.status) {
      this.setState({
        loading: false
      })
    }
  }

  beforeUpload (file) {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
    if (!isJpgOrPng) {
      message.error('请上传JPG/PNG格式的图片!')
      this.setState({
        loading: false
      })
      return false
    }
    const isLt2M = file.size / 1024 / 1024 < 64
    if (!isLt2M) {
      message.error('图片大小 64MB!')
      this.setState({
        loading: false
      })
      return false
    }
    return isJpgOrPng && isLt2M
  }

  handleOk () {
    const { radio, formStatus, editParams } = this.state
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        values.startTime = values.startTime && values.startTime.format('YYYY-MM-DD HH:mm:ss')
        values.endTime = values.endTime && values.endTime.format('YYYY-MM-DD HH:mm:ss')
        values.video = radio || values.video
        values.name = values.radioName
        delete values.radioName
        if (formStatus === 'edit') {
          values.id = editParams.id
          this.props.editRadio(values)
        } else {
          this.props.createRadio(values)
        }
      }
    })
  }

  componentDidMount () {
    const { pageSize, pageNo } = this.state
    this.props.getRadioList({
      pageSize,
      pageNo
    })
  }

  componentWillReceiveProps (nextProps) {
    if (!this.props.createRadioRequest && nextProps.createRadioRequest) {
      message.success('新增成功')
      this.setState({
        showModal: false
      })
      this.search()
    }

    if (!this.props.editRadioRequest && nextProps.editRadioRequest) {
      message.success('编辑成功')
      this.setState({
        showModal: false
      })
      this.search()
    }

    if (!this.props.delRadioRequest && nextProps.delRadioRequest) {
      message.success('删除成功')
      this.search()
    }

    if (!this.props.radioStatusRequest && nextProps.radioStatusRequest) {
      message.success('操作成功')
    }
  }

  render () {
    const { getFieldDecorator } = this.props.form

    const { pageNo, pageSize, selectedRowKeys, showModal, title, editParams, loading, radio } = this.state
    const { form, radioData } = this.props
    const pagination = {
      showSizeChanger: true,
      current: pageNo,
      total: radioData && radioData.total,
      onChange: this.onPageChange,
      pageSize,
      onShowSizeChange: this.onShowSizeChange
    }

    const uploadButton = (
      <div className={Style[`${radio ? '' : 'image-container'}`]}>
        {
          radio ? <div className={Style['banner-image']} style={{ backgroundImage: `url(${radio})` }} /> : <>
            <Icon type={loading ? 'loading' : 'plus'} />
            <div className={Style['ant-upload-text']}>Upload</div></>
        }
      </div>
    )

    return (
      <>
        <ContentBox>
          <div className={Style['scenes-RecycleForm']}>
            <Filters
              cols={this.getFilterCols()}
              form={form}
              search={this.search}
              reset={this.reset} >
              <Button type='primary' onClick={this.handleAdd}>添加视频广告</Button>
              {/* <Button onClick={this.delAll}>批量删除</Button> */}
            </Filters>
            <CustomTable
              selectedRowKeys={selectedRowKeys}
              multipleSelect={this.onSelectChange}
              // multiple
              loading={!radioData} columns={this.getTableCols()}
              dataSource={(radioData && radioData.list) || []}
              pagination={pagination} />
            <Modal
              title={title}
              visible={showModal}
              width={600}
              onOk={this.handleOk}
              destroyOnClose
              onCancel={this.handleCancel}
            >
              <Form {...formItemLayout}>
                <Form.Item label='视频广告名称'>
                  {getFieldDecorator('radioName', {
                    rules: [{ required: true, message: '请输入视频广告名称' }],
                    initialValue: editParams.name
                  })(
                    <Input placeholder='请输入视频广告名称' />
                  )}
                </Form.Item>
                <Form.Item label='视频长度' extra='视频广告时长-单位秒'>
                  {getFieldDecorator('timeLength', {
                    rules: [{ required: true,
                      validator: (rule, value, callback) => {
                        try {
                          if (!value) {
                            throw new Error('请输入视频长度')
                          } if (parseInt(value) <= 0) {
                            throw new Error('时长必须大于0')
                          } else if (!/^[1-9]\d*$/.test(Number(value))) {
                            throw new Error('请输入正确的时长')
                          } else {
                            callback()
                          }
                        } catch (err) {
                          callback(err)
                        }
                      } }],
                    initialValue: editParams.timeLength
                  })(
                    <Input type='number' placeholder='请输入视频长度' />
                  )}
                </Form.Item>
                <Form.Item label='开始时间'>
                  {getFieldDecorator('startTime', {
                    rules: [{ required: true,
                      message: '请选择'
                    }],
                    initialValue: editParams.startTime && moment(editParams.startTime)
                  })(
                    <DatePicker placeholder='请选择' />
                  )}
                </Form.Item>
                <Form.Item label='到期时间'>
                  {getFieldDecorator('endTime', {
                    rules: [{ required: true, message: '请选择' }],
                    initialValue: editParams.endTime && moment(editParams.endTime)
                  })(
                    <DatePicker placeholder='请选择' />
                  )}
                </Form.Item>
                <Form.Item label='上线/下线'>
                  {getFieldDecorator('status', {
                    valuePropName: 'radio',
                    initialValue: editParams.status || 1
                  })(
                    <Radio.Group defaultValue={1}>
                      <Radio value={1}>上线</Radio>
                      <Radio value={0}>下线</Radio>
                    </Radio.Group>)}
                </Form.Item>
                <Form.Item label='视频文件'>
                  {getFieldDecorator('video', {
                    valuePropName: 'picture',
                    initialValue: radio,
                    rules: [{ required: true, message: '视频文件' }]
                  })(
                    <Upload
                      action='/file/upload/1.0'
                      name='file'
                      onChange={this.imageChange}
                      showUploadList={false}
                      withCredentials
                      beforeUpload={this.beforeUpload}
                      headers={{
                        token: localStorage.getItem('token') || ''
                      }}
                    >
                      {uploadButton}
                      <Button type='primary'>
                        <Icon type='cloud-upload' /> 选择上传图片
                      </Button>
                    </Upload>
                  )}
                </Form.Item>
                <Form.Item label='备注'>
                  {getFieldDecorator('remark', {
                    initialValue: editParams.remark
                  })(
                    <TextArea placeholder='请输入内容' />
                  )}
                </Form.Item>
              </Form>
            </Modal>
          </div>
        </ContentBox>
      </>
    )
  }
}

const mapState = state => ({
  radioData: state.operation.radioData,
  createRadioRequest: state.operation.createRadioRequest,
  editRadioRequest: state.operation.editRadioRequest,
  delRadioRequest: state.operation.delRadioRequest,
  radioStatusRequest: state.operation.radioStatusRequest
})
const mapDispatch = dispatch => ({
  getRadioList: dispatch.operation.getRadioList,
  createRadio: dispatch.operation.createRadio,
  editRadio: dispatch.operation.editRadio,
  delRadio: dispatch.operation.delRadio,
  changeRadioStatus: dispatch.operation.changeRadioStatus
})

const Index = Form.create()(IndexForm)

export default createContainer(
  connect(
    mapState,
    mapDispatch
  )(Index)
)
